
import logging
from django.db.models import Q
from django.utils import timezone
from django.shortcuts import get_object_or_404

from rest_framework import status, viewsets, mixins, filters
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import action
from django_filters.rest_framework import DjangoFilterBackend

from .models import Notification, NotificationTemplate, WechatSubscription, MessageRecord
from .serializers import (
    NotificationSerializer, NotificationCreateSerializer,
    NotificationTemplateSerializer, WechatSubscriptionSerializer,
    WechatSubscriptionCreateSerializer, MessageRecordSerializer,
    NotificationListSerializer
)
from user_app.models import User

logger = logging.getLogger(__name__)


class NotificationViewSet(viewsets.ModelViewSet):
    """通知视图集"""
    
    queryset = Notification.objects.all()
    serializer_class = NotificationSerializer
    permission_classes = [IsAuthenticated]
    filter_backends = [DjangoFilterBackend, filters.OrderingFilter]
    filterset_fields = ['notification_type', 'level', 'is_read']
    ordering_fields = ['created_at']
    ordering = ['-created_at']
    
    def get_serializer_class(self):
        """根据操作选择序列化器"""
        if self.action == 'create':
            return NotificationCreateSerializer
        elif self.action == 'list' or self.action == 'my_notifications':
            return NotificationListSerializer
        return self.serializer_class
    
    def get_queryset(self):
        """获取查询集"""
        queryset = super().get_queryset()
        
        # 如果是获取我的通知，则只返回当前用户的通知
        if self.action == 'my_notifications':
            return queryset.filter(recipient=self.request.user)
        
        return queryset
    
    def create(self, request, *args, **kwargs):
        """创建通知"""
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        
        # 创建通知
        notification = Notification.objects.create(
            recipient=serializer.validated_data.get('recipient'),
            title=serializer.validated_data.get('title'),
            content=serializer.validated_data.get('content'),
            notification_type=serializer.validated_data.get('notification_type'),
            level=serializer.validated_data.get('level'),
            related_order=serializer.validated_data.get('related_order')
        )
        
        # 发送消息（微信模板消息、短信等）
        from notification_app.utils import send_websocket_notification
        
        # 通过WebSocket推送通知
        send_websocket_notification(notification)
        
        # 根据通知类型和用户偏好发送不同类型的消息
        if notification.recipient and notification.notification_type:
            # 检查用户是否订阅了微信消息
            wechat_subscriptions = notification.recipient.wechat_subscriptions.filter(
                is_active=True,
                template_type=notification.notification_type
            )
            
            # 发送微信模板消息
            if wechat_subscriptions.exists():
                from notification_app.utils import send_wechat_template_message
                for subscription in wechat_subscriptions:
                    # 准备模板数据
                    template_data = {
                        "first": {"value": notification.title, "color": "#173177"},
                        "keyword1": {"value": notification.content, "color": "#173177"},
                        "keyword2": {"value": notification.created_at.strftime("%Y-%m-%d %H:%M:%S"), "color": "#173177"},
                        "remark": {"value": "点击查看详情", "color": "#173177"}
                    }
                    
                    # 发送微信模板消息
                    send_wechat_template_message(
                        openid=subscription.openid,
                        template_id=subscription.template_id,
                        data=template_data,
                        url=f"https://example.com/notifications/{notification.id}"
                    )
            
            # 检查是否需要发送短信
            if notification.recipient.phone and notification.recipient.sms_notification_enabled:
                from notification_app.utils import send_sms
                # 发送短信通知
                send_sms(
                    phone=notification.recipient.phone,
                    content=f"{notification.title}: {notification.content}"
                )
        
        return Response(
            NotificationSerializer(notification).data,
            status=status.HTTP_201_CREATED
        )
    
    @action(detail=False, methods=['get'])
    def my_notifications(self, request):
        """获取我的通知列表"""
        queryset = self.get_queryset()
        
        # 根据是否已读筛选
        is_read = request.query_params.get('is_read')
        if is_read is not None:
            queryset = queryset.filter(is_read=is_read.lower() == 'true')
        
        # 根据类型筛选
        notification_type = request.query_params.get('notification_type')
        if notification_type:
            queryset = queryset.filter(notification_type=notification_type)
        
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)
    
    @action(detail=True, methods=['post'])
    def mark_as_read(self, request, pk=None):
        """标记通知为已读"""
        notification = self.get_object()
        
        # 检查当前用户是否是通知的接收者
        if notification.recipient != request.user:
            return Response(
                {'error': '只能标记自己的通知为已读'},
                status=status.HTTP_403_FORBIDDEN
            )
        
        if not notification.is_read:
            notification.is_read = True
            notification.read_at = timezone.now()
            notification.save()
        
        return Response(NotificationSerializer(notification).data)
    
    @action(detail=False, methods=['post'])
    def mark_all_as_read(self, request):
        """标记所有通知为已读"""
        queryset = self.get_queryset().filter(recipient=request.user, is_read=False)
        
        updated_count = queryset.update(
            is_read=True,
            read_at=timezone.now()
        )
        
        return Response({'message': f'成功标记{updated_count}条通知为已读'})


class NotificationTemplateViewSet(viewsets.ModelViewSet):
    """通知模板视图集"""
    
    queryset = NotificationTemplate.objects.all()
    serializer_class = NotificationTemplateSerializer
    permission_classes = [IsAuthenticated]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    filterset_fields = ['notification_type', 'is_active']
    search_fields = ['code', 'title_template', 'content_template']


class WechatSubscriptionViewSet(viewsets.ModelViewSet):
    """微信订阅消息视图集"""
    
    queryset = WechatSubscription.objects.all()
    serializer_class = WechatSubscriptionSerializer
    permission_classes = [IsAuthenticated]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['is_active']
    
    def get_serializer_class(self):
        """根据操作选择序列化器"""
        if self.action == 'create':
            return WechatSubscriptionCreateSerializer
        return self.serializer_class
    
    def get_queryset(self):
        """获取查询集"""
        queryset = super().get_queryset()
        
        # 只返回当前用户的订阅
        return queryset.filter(user=self.request.user)
    
    def create(self, request, *args, **kwargs):
        """创建微信订阅"""
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        
        # 创建订阅
        subscription = WechatSubscription.objects.create(
            user=request.user,
            template_id=serializer.validated_data.get('template_id'),
            subscription_id=serializer.validated_data.get('subscription_id'),
            expires_at=serializer.validated_data.get('expires_at')
        )
        
        return Response(
            WechatSubscriptionSerializer(subscription).data,
            status=status.HTTP_201_CREATED
        )


class MessageRecordViewSet(viewsets.ReadOnlyModelViewSet):
    """消息发送记录视图集"""
    
    queryset = MessageRecord.objects.all()
    serializer_class = MessageRecordSerializer
    permission_classes = [IsAuthenticated]
    filter_backends = [DjangoFilterBackend, filters.OrderingFilter]
    filterset_fields = ['message_type', 'status']
    ordering_fields = ['created_at']
    ordering = ['-created_at']
    
    def get_queryset(self):
        """获取查询集"""
        queryset = super().get_queryset()
        
        # 只返回与当前用户相关的消息记录
        return queryset.filter(
            Q(notification__recipient=self.request.user) |
            Q(recipient_id=self.request.user.id)
        )